package selef.xiafan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import selef.xiafan.dto.UserDTO;
import selef.xiafan.entity.user.User;
import selef.xiafan.query.UserQ;
import selef.xiafan.service.IUserService;
import selef.xiafan.util.result.PageResult;
import selef.xiafan.util.result.Result;
import selef.xiafan.util.result.ResultFactory;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/system")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @PostMapping("/users")
    public PageResult<User> userList(@RequestBody UserQ userQ) {
        return iUserService.findAll(userQ);
    }

    /*
     * 查询当前用户是否有管理员权限
     * */
    @GetMapping("/user/isAdmin/{id}")
    public Result userIsAdmin(@PathVariable("id") Integer id) {
        return ResultFactory.buildSuccessResult(iUserService.isAdmin(id));
    }

    @PutMapping("/user/changeEnable")
    public Result changeEnable(@RequestBody User user) {
        Boolean ischange = iUserService.changeEnable(user.getId());
        if (ischange) {
            return ResultFactory.buildSuccessResult("用户状态更新成功");
        }
        return ResultFactory.buildFailResult("用户状态更新失败");
    }

    @PostMapping("/user/delete")
    public Result delete(@RequestBody User user) {
        iUserService.delete(user);
        boolean exist = iUserService.isExist(user.getUsername());
        if (!exist) {
            return ResultFactory.buildSuccessResult("删除成功");
        } else {
            return ResultFactory.buildFailResult("删除失败");
        }
    }

    @PostMapping("/user/edit")
    public void edit(@RequestBody UserDTO userDTO) {
        iUserService.edit(userDTO);
    }

    @PostMapping("/user/restPassword")
    public Result restPassword(@RequestBody User user) {
        iUserService.restPassword(user);
        return ResultFactory.buildSuccessResult("修改成功");
    }

    @PostMapping("/user/batchDelete")
    public Result batchDelete(@RequestBody List<User> user){
        try {
            iUserService.batchDelete(user);
            return new ResultFactory().buildSuccessResult("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultFactory().buildFailResult("删除失败");
        }
    }

}
